<template>
<view class="move-container">
    <view class="form-section">
      
      <view class="form-item">
        <text class="label">地码
          <text class="required">*</text>
        </text>
        <input
            v-model="formData.fromLocation"
            class="input"
            type="text"
            placeholder="请扫描或输入地码"
        />
      </view>

      <view class="form-item">
        <text class="label">目标库位
          <text class="required">*</text>
        </text>
        <input
            v-model="formData.location"
            class="input"
            type="text"
            placeholder="请输入目标库位"
        />
      </view>

<!--      <view class="form-item">-->
<!--        <text class="label">目标库位-->
<!--          <text class="required">*</text>-->
<!--        </text>-->
<!--        &lt;!&ndash; 区域下拉选择框，与呼叫页面一致，仅保留区域相关 &ndash;&gt;-->
<!--        <picker-->
<!--            mode="selector"-->
<!--            :range="areaList"-->
<!--            range-key="loc"-->
<!--            @click="handleAreaPickerTap"-->
<!--            @change="handleAreaChange"-->
<!--        >-->
<!--          <view class="input">-->
<!--            {{ selectedAreaName || '请选择目标库位' }}-->
<!--          </view>-->
<!--        </picker>-->
<!--      </view>-->



<!--      <view class="form-item">-->
<!--        <text class="label">托盘号-->
<!--        </text>-->
<!--        <input-->
<!--            v-model="formData.pallet"-->
<!--            class="input"-->
<!--            type="text"-->
<!--            placeholder="请扫描或输入托盘号"-->
<!--        />-->
<!--      </view>-->

<!--      <view class="form-item">-->
<!--        <text class="label">物料名称-->
<!--        </text>-->
<!--        <input-->
<!--            v-model="formData.goodsName"-->
<!--            class="input"-->
<!--            type="text"-->
<!--            placeholder="请输入物料名称"-->
<!--        />-->
<!--      </view>-->

<!--      <view class="form-item">-->
<!--        <text class="label">箱号-->
<!--        </text>-->
<!--        <input-->
<!--            v-model="formData.type"-->
<!--            class="input"-->
<!--            type="text"-->
<!--            placeholder="请扫描或输入箱号"-->
<!--        />-->
<!--      </view>-->

<!--      <view class="form-item">-->
<!--        <text class="label">终点库位-->
<!--          <text class="required">*</text>-->
<!--        </text>-->
<!--        <input-->
<!--            v-model="formData.toLocation"-->
<!--            class="input"-->
<!--            type="text"-->
<!--            placeholder="请扫描或输入终点库位"-->
<!--        />-->
<!--      </view>-->
	  
	 <!-- <view class="form-item">
	    <text class="label">任务类型
	      <text class="required">*</text>
	    </text>
	    <picker 
	      mode="selector" 
	      :range="taskType" 
	      range-key="label" 
	      @change="onBillChange" 
	      :value="billIndex">
	      <view class="input">
	        {{ taskType[billIndex] ? taskType[billIndex].label : '请选择任务类型' }} 
	      </view>
	    </picker>
	  </view>
	  
	  <view class="form-item">
	    <text class="label">车辆
	      <text class="required">*</text>
	    </text>-->

<!-- 	    <picker 
	      mode="selector" 
	      :range="chooseAGV" 
	      range-key="label" 
	      @change="chooseAGVcar" 
	      :value="agvId">
	      <view class="input">
	        {{ chooseAGV[agvId] ? chooseAGV[agvId].label : '请选择车辆' }} 
	      </view>
	    </picker>
	  </view> -->

     

      <view class="btn-group">
     <!--   <button @click="handleReset" class="btn btn-default">重置</button> -->
        <button @click="handleSubmit" class="btn btn-primary" :disabled="loading">
          <text v-if="loading" class="cuIcon-loading2 iconfont-spin"></text>
          {{ loading ? '提交中...' : '创建任务' }}
        </button>
      </view>
    </view>
  </view>
</template>

<script>
	
import {psTask} from '@/api/system/stock';
import {listAreas, listRest, listSites} from "../../api/system/site";

var main, receiver, filter;

export default {
  data() {
    return {
	taskType: [
        {value: '2', label: '入库'},
        {value: '1', label: '出库'},
      ],
	  chooseAGV:[],
	   billIndex: null,
	   agvId: 0,
      formData: {
	    // instrock: '',
		taskType: '',
        fromLocation: '',
		agvId: '',
        toLocation: '',
        siteType: '',
        // remark: ''
      },
      loading: false,
      areaList: [],
      selectedAreaName: ''
    };
  },

  onLoad() {
    this.initScan();
  },

  onShow() {
    this.startScan();
  },

  onHide() {
    this.stopScan();
  },

  onUnload() {
    this.stopScan();
  },

  methods: {
	   onBillChange(e) {
		  
	        this.billIndex = e.detail.value;
			 console.log("this.billIndex",this.billIndex)
	        this.formData.taskType = this.taskType[this.billIndex].value;
	      },
		  chooseAGVcar(e) {
	        this.agvId = e.detail.value;
	        this.formData.chooseAGV = this.chooseAGV[this.agvId].value;
	      },
    initScan() {
      let _this = this;
      /* #ifdef APP-PLUS */
      main = plus.android.runtimeMainActivity();
      var IntentFilter = plus.android.importClass('android.content.IntentFilter');
      filter = new IntentFilter();
      filter.addAction("com.service.scanner.data")
      receiver = plus.android.implements('io.dcloud.feature.internal.reflect.BroadcastReceiver', {
        onReceive: function (context, intent) {
          plus.android.importClass(intent);
          let code = intent.getStringExtra("ScanCode");
          console.log(code)
          _this.handleScanResult(code);
        }
      });
      /* #endif */
    },

    startScan() {
      /* #ifdef APP-PLUS */
      main.registerReceiver(receiver, filter);
      /* #endif */
    },

    stopScan() {
      /* #ifdef APP-PLUS */
      main.unregisterReceiver(receiver);
      /* #endif */
    },

    // 处理扫码结果
    handleScanResult(code) {
      // 判断扫码内容类型
      if (code.startsWith('L')) {
        // 库位格式
        if (!this.formData.fromLocation) {
          this.formData.fromLocation = code.substring(1);
        } else if (!this.formData.toLocation) {
          this.formData.toLocation = code.substring(1);
        }
      } else if (code.startsWith('M')) {
        // 物料编号格式
        this.formData.materialCode = code.substring(1);
      } else {
        // 默认当作物料编号处理
        this.formData.materialCode = code;
      }
    },

    // 重置表单
    handleReset() {
      this.formData = {
        fromLocation: '',
        toLocation: '',
        taskType: '',
        remark: '',
        location:''
      };
	  this.billIndex = null
    },

    handleAreaPickerTap() {
      // if (!this.areaList.length) {
      listRest().then(response => {
          console.log('区域接口返回：', response);
          this.areaList = response.rows || [];
        }).catch(error => {
          console.error('获取区域数据失败:', error);
        });
      // }
    },

    handleAreaChange(e) {
      const index = e.detail.value;
      const selected = this.areaList[index];
      if (selected) {
        this.selectedAreaName = selected.loc || '未知区域';
        this.formData.location = selected.loc;
      }
    },



    fetchMaterialListByArea(area) {
      listSites({ siteType: area.dictValue }).then(response => {
        this.materialList = (response.rows || []).map(item => ({
          ...item,
          displayText: [item.remark, item.goodsName, item.type].filter(Boolean).join(' / ')
        }));
        this.selectedMaterialName = '';
        this.formData.fromLocation = '';
      }).catch(error => {
        this.materialList = [];
        this.selectedMaterialName = '';
        this.formData.fromLocation = '';
        console.error('获取物料信息失败:', error);
      });
    },

    // 提交表单
    handleSubmit() {
      if (this.loading) return;

      // 表单验证
      if (!this.formData.fromLocation) {
        this.$modal.msgError('请输入地码');
        return;
      }
      if (!this.formData.location) {
        this.$modal.msgError('请输入库位');
        return;
      }
      // if (!this.formData.toLocation) {
      //   this.$modal.msgError('请输入终点库位');
      //   return;
      // }
	  // if (!this.formData.taskType) {
	  //   this.$modal.msgError('请输入任务类型');
	  //   return;
	  // }
 

      this.loading = true;
      this.formData.taskType = '手工任务'
      psTask(this.formData)
          .then(res => {
			  console.log(res+"songmuyan")
            if (res.code === 200) {
              this.$modal.msgSuccess('任务成功');
              this.handleReset();
            } else {
              this.$modal.msgError(res.msg || '任务失败');
            }
          })
          .catch(error => {
            console.error('任务失败:', error);
            this.$modal.msgError('任务失败');
          })
          .finally(() => {
            this.loading = false;
          });
    }
  }
}
</script>

<style lang="scss" scoped>
	/* 样式保持不变 */
	.move-container {
	  min-height: 100vh;
	  background-color: #f8f9fa;
	  padding: 16px;
	}
.move-container {
  min-height: 100vh;
  background-color: #f8f9fa;
  padding: 16px;
}

.form-section {
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;

  .form-item {
    margin-bottom: 16px;

    .label {
      display: block;
      font-size: 14px;
      color: #333;
      margin-bottom: 8px;
      font-weight: 500;

      .required {
        color: #ff4d4f;
        margin-left: 4px;
      }
    }

    .input {
      width: 100%;
      height: 40px;
      background-color: #f8f9fa;
      border-radius: 4px;
      padding: 0 12px;
      font-size: 14px;
      color: #333;
      display: flex;
      align-items: center;
    }
  }
}

.btn-group {
  display: flex;
  justify-content: space-between;
  margin-top: 24px;

  .btn {
    width: 48%;
    height: 40px;
    border-radius: 4px;
    font-size: 14px;
    font-weight: 500;

    &.btn-default {
      background-color: #f8f9fa;
      color: #666;
    }

    &.btn-primary {
      background-color: #4A90E2;
      color: #fff;

      &:disabled {
        opacity: 0.7;
      }
    }
  }
}

.iconfont-spin {
  display: inline-block;
  animation: loading-rotate 2s linear infinite;
}

@keyframes loading-rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>